const mysql2 = require("mysql2");
const { dbConfig } = require("../config/application.config");

const Pool = mysql2.createPool({
  host: dbConfig.host,
  user: dbConfig.user,
  password: dbConfig.password,
  database: dbConfig.database,
});

// 封装数据库查询方法
function poolQuery(sql, params, callback) {
  Pool.getConnection((err, connection) => {
    try {
      if (err) {
        console.error("获取数据库连接失败:", err);
        return callback(err, null);
      }

      connection.query(sql, params, (error, results) => {
        if (error) {
          console.error("数据库查询失败:", error);
          return callback(error, null);
        }

        // 处理查询结果
        callback(null, results);
      });
    } catch (err) {
      console.log(err);
    } finally {
      console.log("释放数据库连接");
      connection.release(); // 释放连接到连接池
    }
  });
}
module.exports = { Pool, poolQuery };
